package com.per.mybootall.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2022/6/8
 * Time: 18:33
 * Description:
 */
public class test22 {
  public static void main(String[] args) {
    Map<Object, Map> tempMap = new HashMap();
    List<Map> tree = new ArrayList<>();
    List<Map> initList=new ArrayList(){{
      add(new HashMap(){{put("id",10);put("parent_id",0);}});
      add(new HashMap(){{put("id",3);put("parent_id",2);}});
      add(new HashMap(){{put("id",2);put("parent_id",10);}});

    }};
    System.out.println(JSONObject.toJSONString(formatTree(initList)));

  }


  public static <T extends Map> List<T> formatTree(List<T> list) {
    List<T> nodeList = new ArrayList<T>();
    for (T node1 : list) {
      boolean mark = false;
      for (T node2 : list) {
        if (node1.get("parent_id") != null && (node1.get("parent_id").toString()).equals((node2.get("id").toString()))) {
          mark = true;
          if (node2.get("children") == null) {
            node2.put("children", new ArrayList<T>());
          }
          ArrayList children = (ArrayList) node2.get("children");
          children.add(node1);
          node2.put("children", children);
          break;
        }
      }
      if (!mark) {
        nodeList.add(node1);
      }
    }
    return nodeList;
  }
}
